package com.cooba.activitys.Living;

import android.Manifest;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.cooba.R;
import com.cooba.bean.LivingDetailBean;
import com.cooba.mqtt.MqttBroker;
import com.cooba.upload.CustomMultipartEntity;
import com.cooba.utils.BitmapZipUtil;
import com.cooba.utils.CommonUtil;
import com.cooba.utils.ServerURL;
import com.cooba.views.FlowLayout;
import com.cooba.views.MyCustomScrollview;
import com.cooba.views.ProgressImageView;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.Inflater;

import me.nereo.multi_image_selector.MultiImageSelector;
import me.nereo.multi_image_selector.bean.Image;

public class LivingContentAddNew1Activity extends AppCompatActivity implements View.OnClickListener {
    private static final int REQUEST_IMAGE = 0;
    protected static final int REQUEST_STORAGE_READ_ACCESS_PERMISSION = 101;
    protected static final int REQUEST_STORAGE_WRITE_ACCESS_PERMISSION = 102;

    private LinearLayout living_root_ll;
    private ImageButton add_content_new_back_ib;
    private LinearLayout living_add_content_new1_ll;
    private ImageView living_add_content_new1_add_text_iv;
    private ImageView living_add_content_new1_add_image_iv;
    private TextView add_content_new1_finish_tv;
    private EditText add_content_new1_title_et;
    private ScrollView living_add_content_new1_sv;
    private LinearLayout living_add_content_new1_add_dong_ll;
    private LinearLayout living_add_content_new1_add_jinzhi_ll;
    private ImageView living_add_content_new1_add_text_jinzhi_iv;
    private ImageView living_add_content_new1_add_image_jingzhi_iv;
    private int[] location = new int[2];
    private int[] location2 = new int[2];

    private int editID = 0;

    private int i = 0;
    private ArrayList<String> mSelectPath = new ArrayList<>();
    private ArrayList<File> fileList = new ArrayList<>();
    private HttpMultipartPost post;
    private StringBuilder sburl;
    private Dialog dialog;
    private LayoutInflater li;
    private ProgressImageView imageView;
    private TextView upload_image_progress_tv;

    private List<Map<Integer, String>> urllist = new ArrayList<>();
    private Map<Integer, String> mapurl = new HashMap<>();
    Map<Integer, String> imagesizemap = new HashMap<>();
    private List<LivingDetailBean.LivingDetailContent> contentList = new ArrayList<>();
    private String livie_id;
    private int id;
    private LivingDetailBean livingdetailbean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_living_add_content_new1);
        livie_id = getIntent().getStringExtra("live_id");
        initView();
        initListener();
    }

    private void initListener() {
        add_content_new_back_ib.setOnClickListener(this);
        living_add_content_new1_add_text_iv.setOnClickListener(this);
        living_add_content_new1_add_image_iv.setOnClickListener(this);
        add_content_new1_finish_tv.setOnClickListener(this);
        living_add_content_new1_add_image_jingzhi_iv.setOnClickListener(this);
        living_add_content_new1_add_text_jinzhi_iv.setOnClickListener(this);

        living_add_content_new1_sv.setOnTouchListener(new View.OnTouchListener() {
            private int lastY = 0;
            private int touchEventId = -9983761;
            Handler handler = new Handler() {
                public void handleMessage(Message msg) {
                    super.handleMessage(msg);
                    if (msg.what == touchEventId) {
                        if (lastY != living_add_content_new1_sv.getScrollY()) {
                            //scrollview一直在滚动，会触发
                            handler.sendMessageDelayed(
                                    handler.obtainMessage(touchEventId, living_add_content_new1_sv), 5);
                            lastY = living_add_content_new1_sv.getScrollY();
                            living_add_content_new1_add_dong_ll.getLocationOnScreen(location);
                            living_add_content_new1_add_jinzhi_ll.getLocationOnScreen(location2);
                            //动的到静的位置时，静的显示。动的实际上还是网上滚动，但我们看到的是静止的那个
                            if (location[1] <= location2[1]) {
                                living_add_content_new1_add_jinzhi_ll.setVisibility(View.VISIBLE);
                            } else {
                                //静止的隐藏了
                                living_add_content_new1_add_jinzhi_ll.setVisibility(View.GONE);
                            }
                        }
                    }
                }
            };

            public boolean onTouch(View v, MotionEvent event) {
                //必须两个都搞上，不然会有瑕疵。
                //没有这段，手指按住拖动的时候没有效果
                if (event.getAction() == MotionEvent.ACTION_MOVE) {
                    handler.sendMessageDelayed(
                            handler.obtainMessage(touchEventId, v), 5);
                }
                //没有这段，手指松开scroll继续滚动的时候，没有效果
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    handler.sendMessageDelayed(
                            handler.obtainMessage(touchEventId, v), 5);
                }
                return false;
            }
        });

//        living_root_ll.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
//            @Override
//            public void onGlobalLayout() {
//                int heightDiff = living_root_ll.getRootView().getHeight() - living_root_ll.getHeight();
//                if (heightDiff > 100) { //高度变小100像素则认为键盘弹出
//                    //这里执行需要的处理
//                    living_add_content_new1_sv.fullScroll(ScrollView.FOCUS_DOWN);
//                } else {
//                    // living_add_content_new1_sv.fullScroll(ScrollView.FOCUS_DOWN);
//                }
//            }
//        });
    }

    private void initView() {
        living_root_ll= (LinearLayout) findViewById(R.id.living_root_ll);
        add_content_new_back_ib = (ImageButton) findViewById(R.id.add_content_new_back_ib);
        add_content_new1_title_et = (EditText) findViewById(R.id.add_content_new1_title_et);
        living_add_content_new1_add_text_iv = (ImageView) findViewById(R.id.living_add_content_new1_add_text_iv);
        living_add_content_new1_ll = (LinearLayout) findViewById(R.id.living_add_content_new1_ll);
        add_content_new1_finish_tv = (TextView) findViewById(R.id.add_content_new1_finish_tv);
        living_add_content_new1_add_image_iv = (ImageView) findViewById(R.id.living_add_content_new1_add_image_iv);
        living_add_content_new1_sv = (ScrollView) findViewById(R.id.living_add_content_new1_sv);
        living_add_content_new1_add_dong_ll = (LinearLayout) findViewById(R.id.living_add_content_new1_add_dong_ll);
        living_add_content_new1_add_jinzhi_ll = (LinearLayout) findViewById(R.id.living_add_content_new1_add_jinzhi_ll);
        living_add_content_new1_add_text_jinzhi_iv = (ImageView) findViewById(R.id.living_add_content_new1_add_text_jinzhi_iv);
        living_add_content_new1_add_image_jingzhi_iv = (ImageView) findViewById(R.id.living_add_content_new1_add_image_jingzhi_iv);
        living_add_content_new1_add_jinzhi_ll.setVisibility(View.GONE);
    }

    @Override
    public void onClick(View v) {
        int cout=living_add_content_new1_ll.getChildCount();
        switch (v.getId()) {
            case R.id.add_content_new_back_ib:
                finish();
                break;
            case R.id.living_add_content_new1_add_text_jinzhi_iv:
                if (TextUtils.isEmpty(add_content_new1_title_et.getText().toString())) {
                    Toast.makeText(this, "标题不能为空!", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (cout>10){
                    Toast.makeText(this, "最多只能添加10条数据!", Toast.LENGTH_SHORT).show();
                    return;
                }
                addEditView();
                editID++;

                new Handler().post(new Runnable() {
                    @Override
                    public void run() {
                        living_add_content_new1_sv.fullScroll(ScrollView.FOCUS_DOWN);

                    }
                });
                break;
            case R.id.living_add_content_new1_add_image_jingzhi_iv:
                if (TextUtils.isEmpty(add_content_new1_title_et.getText().toString())) {
                    Toast.makeText(this, "标题不能为空!", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (cout>10){
                    Toast.makeText(this, "最多只能添加10条数据!", Toast.LENGTH_SHORT).show();
                    return;
                }
                addImageView();
                editID++;
                new Handler().post(new Runnable() {
                    @Override
                    public void run() {
                        living_add_content_new1_sv.fullScroll(ScrollView.FOCUS_DOWN);
                    }
                });
                break;
            case R.id.living_add_content_new1_add_text_iv:
                if (TextUtils.isEmpty(add_content_new1_title_et.getText().toString())) {
                    Toast.makeText(this, "标题不能为空!", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (cout>10){
                    Toast.makeText(this, "最多只能添加10条数据!", Toast.LENGTH_SHORT).show();
                    return;
                }
                addEditView();
                editID++;

                new Handler().post(new Runnable() {
                    @Override
                    public void run() {
                        living_add_content_new1_sv.fullScroll(ScrollView.FOCUS_DOWN);

                    }
                });
                break;
            case R.id.living_add_content_new1_add_image_iv:
                if (TextUtils.isEmpty(add_content_new1_title_et.getText().toString())) {
                    Toast.makeText(this, "标题不能为空!", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (cout>10){
                    Toast.makeText(this, "最多只能添加10条数据!", Toast.LENGTH_SHORT).show();
                    return;
                }
                addImageView();
                editID++;
                new Handler().post(new Runnable() {
                    @Override
                    public void run() {
                        living_add_content_new1_sv.fullScroll(ScrollView.FOCUS_DOWN);
                    }
                });
                break;
            case R.id.add_content_new1_finish_tv:
                Log.d("wei", "jahh");
                contentList.clear();
                SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String create_date = sDateFormat.format(new java.util.Date());
                if (TextUtils.isEmpty(add_content_new1_title_et.getText().toString())) {
                    Toast.makeText(this, "标题不能为空!", Toast.LENGTH_SHORT).show();
                    return;
                }

                LivingDetailBean.LivingDetailContent contenttitle = new LivingDetailBean.LivingDetailContent();
                contenttitle.setLiveId(livie_id);
                contenttitle.setIsTitle("1");
                contenttitle.setMessageType("0");
                contenttitle.setMessage(add_content_new1_title_et.getText().toString());
                contenttitle.setWidthHeight("");
                contenttitle.setCreateDate(create_date);
                contentList.add(contenttitle);

                for (int i = 0; i < living_add_content_new1_ll.getChildCount(); i++) {
                    View view = living_add_content_new1_ll.getChildAt(i);
                    if (view instanceof FrameLayout){
                        for (int j=0;j<((FrameLayout) view).getChildCount();j++){
                           View child=((FrameLayout) view).getChildAt(j);
                            if (child instanceof LinearLayout){
                                for (int m=0;m<((LinearLayout) child).getChildCount();m++){
                                   View child_1=((LinearLayout) child).getChildAt(m);
                                    if (child_1 instanceof TextView) {
                                        Log.d("wei", "文字id:" + child_1.getId());
                                        if (!TextUtils.isEmpty(((TextView) child_1).getText())) {
                                            LivingDetailBean.LivingDetailContent content = new LivingDetailBean.LivingDetailContent();
                                            content.setLiveId(livie_id);
                                            content.setIsTitle("0");
                                            content.setMessageType("0");
                                            content.setMessage(((TextView) child_1).getText().toString());
                                            content.setWidthHeight("");
                                            content.setCreateDate(create_date);
                                            contentList.add(content);
                                        }
                                    } else if (child_1 instanceof ImageView) {
                                        //Log.d("wei", "图片id:" + view.getId());
                                        if (mapurl.containsKey(child_1.getId())) {
                                            String message = mapurl.get(child_1.getId());
                                            if (imagesizemap.containsKey(child_1.getId())) {
                                                LivingDetailBean.LivingDetailContent content = new LivingDetailBean.LivingDetailContent();
                                                content.setLiveId(livie_id);
                                                content.setIsTitle("0");
                                                content.setMessageType("1");
                                                content.setMessage(message);
                                                content.setWidthHeight(imagesizemap.get(child_1.getId()));
                                                content.setCreateDate(create_date);
                                                contentList.add(content);
                                            }
                                        }
                                        Log.d("wei", "图片url:" + mapurl.get(child_1.getId()) + ",图片Id:" + child_1.getId());
                                    }
                                }
                            }
                        }
                    }
                }

                Collections.reverse(contentList);
                Log.d("wei", "Json:" + new Gson().toJson(contentList));
                String contentjson = new Gson().toJson(contentList);
                doSubmit(contentjson);

                break;
            default:
                break;
        }
    }

    private void doSubmit(String contentjson) {
        HttpUtils httpUtils = new HttpUtils();
        RequestParams params = new RequestParams();
        params.addBodyParameter("content_list", contentjson);
        httpUtils.send(HttpRequest.HttpMethod.POST, ServerURL.httpUrl + ServerURL.mylivingadd, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Log.d("wei", "直播添加成功" + responseInfo.result);
                try {
                    livingdetailbean = new Gson().fromJson(responseInfo.result, LivingDetailBean.class);
                    if (livingdetailbean.getStatus().equals("1")) {
                        sendMessage(responseInfo.result);
                        setResult(RESULT_OK);
                        finish();
                    }
                } catch (JsonSyntaxException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                Log.d("wei", "直播添加失败" + msg);
            }
        });
    }

    private void sendMessage(final String message) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                new MqttBroker().sendMessage(livie_id, message, LivingContentAddNew1Activity.this);
            }
        }).start();

    }

    private void addImageView() {
        final View image_frame=getLayoutInflater().inflate(R.layout.edit_text_view, null, false);
        ImageView delete_view= (ImageView) image_frame.findViewById(R.id.delete_view);
        LinearLayout ll= (LinearLayout) image_frame.findViewById(R.id.add_view_ll);

        int width = getResources().getDisplayMetrics().widthPixels;
        int height = (int) (width * 0.56);
        ImageView iv = new ImageView(this);
        iv.setId(editID);

        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(width - CommonUtil.dip2px(this, 20), width - CommonUtil.dip2px(this, 20));
        lp.setMargins(CommonUtil.dip2px(this, 10), CommonUtil.dip2px(this, 5), CommonUtil.dip2px(this, 5), CommonUtil.dip2px(this, 10));
        iv.setLayoutParams(lp);
        iv.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
        iv.setImageResource(R.mipmap.upload);
        //living_add_content_new1_ll.addView(iv);
        ll.addView(iv);
        living_add_content_new1_ll.addView(image_frame);
        delete_view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new AlertDialog.Builder(LivingContentAddNew1Activity.this).setMessage("是否删除?").setPositiveButton("是", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        living_add_content_new1_ll.removeView(image_frame);
                    }
                }).setNegativeButton("否", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                }).show();
            }
        });
//        iv.setOnLongClickListener(new View.OnLongClickListener() {
//            @Override
//            public boolean onLongClick(final View v) {
//                new AlertDialog.Builder(LivingContentAddNew1Activity.this).setMessage("是否删除?").setPositiveButton("是", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        dialog.dismiss();
//                        living_add_content_new1_ll.removeView(v);
//                    }
//                }).setNegativeButton("否", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//
//                    }
//                }).show();
//                return false;
//            }
//        });
        iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mapurl.containsKey(v.getId())) {
                    mapurl.remove(v.getId());
                    imagesizemap.remove(v.getId());
                    //urllist.remove(mapurl.get(v.getId()));
                }
                id = v.getId();
                pickImage();
            }
        });

    }

    private void addEditView() {
        final View edit_frame=getLayoutInflater().inflate(R.layout.edit_text_view, null, false);
        ImageView delete_view= (ImageView) edit_frame.findViewById(R.id.delete_view);
        LinearLayout ll= (LinearLayout) edit_frame.findViewById(R.id.add_view_ll);
        EditText editText = new EditText(this);
        editText.setId(editID);
        editText.setLines(5);
        editText.setPadding(10, 10, 10, 10);
        editText.setGravity(Gravity.TOP);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        lp.setMargins(CommonUtil.dip2px(this, 10), CommonUtil.dip2px(this, 10), CommonUtil.dip2px(this, 10), CommonUtil.dip2px(this, 10));
        editText.setLayoutParams(lp);
        editText.setBackgroundResource(R.drawable.edit_bg);
        //living_add_content_new1_ll.addView(editText);
        ll.addView(editText);
        living_add_content_new1_ll.addView(edit_frame);
        delete_view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new AlertDialog.Builder(LivingContentAddNew1Activity.this).setMessage("是否删除?").setPositiveButton("是", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        living_add_content_new1_ll.removeView(edit_frame);
                    }
                }).setNegativeButton("否", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                }).show();
            }
        });
//        editText.setOnLongClickListener(new View.OnLongClickListener() {
//            @Override
//            public boolean onLongClick(final View v) {
//                new AlertDialog.Builder(LivingContentAddNew1Activity.this).setMessage("是否删除?").setPositiveButton("是", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        dialog.dismiss();
//                        living_add_content_new1_ll.removeView(v);
//                    }
//                }).setNegativeButton("否", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//
//                    }
//                }).show();
//                return false;
//            }
//        });
    }

    private void pickImage() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN // Permission was added in API Level 16
                && ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            requestPermission(Manifest.permission.READ_EXTERNAL_STORAGE,
                    getString(R.string.mis_permission_rationale),
                    REQUEST_STORAGE_READ_ACCESS_PERMISSION);
        }
        {
            MultiImageSelector.create(LivingContentAddNew1Activity.this)
                    .showCamera(true) // 是否显示相机. 默认为显示
                    .count(1) // 最大选择图片数量, 默认为9. 只有在选择模式为多选时有效
                    .single() // 多选模式, 默认模式;
                    .start(LivingContentAddNew1Activity.this, REQUEST_IMAGE);
        }
    }

    private void requestPermission(final String permission, String rationale, final int requestCode) {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
            new AlertDialog.Builder(this)
                    .setTitle(R.string.mis_permission_dialog_title)
                    .setMessage(rationale)
                    .setPositiveButton(R.string.mis_permission_dialog_ok, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            ActivityCompat.requestPermissions(LivingContentAddNew1Activity.this, new String[]{permission}, requestCode);
                        }
                    })
                    .setNegativeButton(R.string.mis_permission_dialog_cancel, null)
                    .create().show();
        } else {
            ActivityCompat.requestPermissions(this, new String[]{permission}, requestCode);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == REQUEST_STORAGE_READ_ACCESS_PERMISSION) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                pickImage();
            }
        } else {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_IMAGE) {
            if (resultCode == RESULT_OK) {
                mSelectPath.clear();
                mSelectPath = data.getStringArrayListExtra(MultiImageSelector.EXTRA_RESULT);
                StringBuilder sb = new StringBuilder();
                for (String p : mSelectPath) {
                    sb.append(p);
                    sb.append("\n");
                }

                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inJustDecodeBounds = true;
                Bitmap btemp = BitmapFactory.decodeFile(mSelectPath.get(0), options);
                showUploadDialog();
//                if (options.outWidth>options.outHeight) {
//                }
//                else {
//                    Toast.makeText(LivingContentAddNew1Activity.this, "请上传宽图!", Toast.LENGTH_SHORT).show();
//                }
            }
        }
    }

    private void showUploadDialog() {
        dialog = new Dialog(this);
        li = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
        View v = li.inflate(R.layout.dialog_upload_image, null);
        android.view.Window window = dialog.getWindow();
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(v);
        dialog.setCanceledOnTouchOutside(false);
        //window.getDecorView().setPadding(0, 0, 0, 0);
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setAttributes(lp);
        window.setBackgroundDrawableResource(android.R.color.transparent);
        window.setGravity(Gravity.CENTER);
        dialog.show();
        imageView = (ProgressImageView) v.findViewById(R.id.upload_image_progress_iv);
        upload_image_progress_tv = (TextView) v.findViewById(R.id.upload_image_progress_tv);
        TextView cancel = (TextView) v.findViewById(R.id.upload_image_progress_cancel);
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                if (post.isCancelled()) {
                    post.cancel(true);
                }
            }
        });
        fileList.clear();
        i = 0;
        for (int i = 0; i < mSelectPath.size(); i++) {
            File file = BitmapZipUtil.scal(mSelectPath.get(i), LivingContentAddNew1Activity.this);
            fileList.add(file);
        }

        Bitmap bitmap = BitmapFactory.decodeFile(fileList.get(0).getPath());
        imageView.setImageBitmap(bitmap);
        upload();
    }


    private void upload() {
        post = new HttpMultipartPost(LivingContentAddNew1Activity.this, fileList.get(i).getPath(), ServerURL.httpUrl + ServerURL.uploadImg);
        post.execute();
    }

    class HttpMultipartPost extends AsyncTask<String, Integer, String> {

        private Context context;
        private String filePath;
        //private ProgressDialog pd;
        private long totalSize;
        private String requestUrl;

        public HttpMultipartPost(Context context, String filePath, String requestUrl) {
            this.context = context;
            this.filePath = filePath;
            this.requestUrl = requestUrl;
        }

        @Override
        protected void onPreExecute() {
            upload_image_progress_tv.setText("正在上传(" + (i + 1) + "/" + fileList.size() + ")");
        }

        @Override
        protected String doInBackground(String... params) {
            String serverResponse = null;
            HttpClient httpClient = new DefaultHttpClient();
            HttpContext httpContext = new BasicHttpContext();
            HttpPost httpPost = new HttpPost(requestUrl);

            try {
                CustomMultipartEntity multipartContent = new CustomMultipartEntity(
                        new CustomMultipartEntity.ProgressListener() {
                            @Override
                            public void transferred(long num) {
                                publishProgress((int) ((num / (float) totalSize) * 100));
                            }
                        });

                // 使用FileBody上传图片
                multipartContent.addPart("value", new FileBody(new File(filePath)));
                totalSize = multipartContent.getContentLength();
                // 上传
                httpPost.setEntity(multipartContent);
                HttpResponse response = httpClient.execute(httpPost, httpContext);
                serverResponse = EntityUtils.toString(response.getEntity());
            } catch (Exception e) {
                e.printStackTrace();
            }
            return serverResponse;
        }

        @Override
        protected void onProgressUpdate(Integer... progress) {
            imageView.setProgress((int) (progress[0]));
        }

        @Override
        protected void onPostExecute(String result) {
            System.out.println("result: " + result);
            JSONObject jsonObject = null;
            try {
                jsonObject = new JSONObject(result.toString());
                String status = jsonObject.get("status").toString();
                if (status.equals("1")) {
                    String url = jsonObject.get("url").toString();
                    mapurl.put(id, url);
                    //urllist.add(mapurl);
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inJustDecodeBounds = true;
                    StringBuilder sbwh = new StringBuilder();
                    for (int i = 0; i < fileList.size(); i++) {
                        Bitmap btemp = BitmapFactory.decodeFile(fileList.get(i).getPath(), options);
                        sbwh.append("" + options.outWidth + "*" + options.outHeight);
                        sbwh.append("#");
                    }
                    imagesizemap.put(id, sbwh.toString());
                    i++;
                    if (i < fileList.size()) {
                        upload();
                    } else {
                        dialog.dismiss();
                        int width = context.getResources().getDisplayMetrics().widthPixels;
                        int height = (int) (width * 0.56);
                        LinearLayout.LayoutParams lp;
                        lp = new LinearLayout.LayoutParams(width - 40, width - 40);
                        lp.setMargins(20, 20, 20, 20);
                        findViewById(id).setLayoutParams(lp);
                        Bitmap bitmap = BitmapFactory.decodeFile(fileList.get(0).getPath());
                        ((ImageView) findViewById(id)).setScaleType(ImageView.ScaleType.CENTER_CROP);
                        ((ImageView) findViewById(id)).setImageBitmap(bitmap);

                    }
                } else {
                    Toast.makeText(LivingContentAddNew1Activity.this, "上传失败", Toast.LENGTH_SHORT).show();
                    dialog.dismiss();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        protected void onCancelled() {
            System.out.println("cancle");
        }

    }

}
